package com.chaihu.api.listener.user.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.api.listener.AbstractServiceApiListener;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.in.user.userinfo.QueryUserIn;
import com.chaihu.bean.out.user.userinfo.QueryUserOut;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.annotation.ChaihuListener;
import com.chaihu.core.context.DataFlowContext;
import com.chaihu.core.event.service.api.ServiceDataFlowEvent;
import com.chaihu.intf.user.QueryUsersService;
import com.chaihu.utils.constant.ServiceCodeConstant;
import com.chaihu.utils.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author chaihu
 * @date 2021/10/13
 */
@Slf4j
@ChaihuListener("queryUserListener")
public class QueryUserListener extends AbstractServiceApiListener {

    @Autowired
    private QueryUsersService queryUsersService;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        log.info("========= json 入参：{}", reqJson.toJSONString());

        Assert.hasKeyAndValue(reqJson,"userId", MsgCode.SUCCESS.getMsg());
    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        String userId = reqJson.getString("userId");

        QueryUserIn queryUserIn = new QueryUserIn();
        queryUserIn.setUserId(userId);
        ResponseResult<List<QueryUserOut>> queryUsersResponseResult = queryUsersService.queryUsers(queryUserIn);
        if (!StringUtils.equals(MsgCode.SUCCESS.getCode(), queryUsersResponseResult.getCode()) || CollectionUtils.isEmpty(queryUsersResponseResult.getData())) {
            ResponseEntity<String> responseEntity = new ResponseEntity<>(JSONObject.toJSONString(queryUsersResponseResult), HttpStatus.OK);
            context.setResponseEntity(responseEntity);
            return;
        }
        QueryUserOut queryUserOut = queryUsersResponseResult.getData().get(0);
        queryUserOut.setPassword(null);
        ResponseEntity<String> responseEntity = new ResponseEntity<>(JSON.toJSONString(queryUserOut), HttpStatus.OK);
        context.setResponseEntity(responseEntity);
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeConstant.SERVICE_CODE_USER_QUERY_USER_INFO;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.GET;
    }
}
